<template>
  <div>
    <el-form ref="ruleForm" label-position="right" size="small" label-width="70px" class="base-search-more">
       <el-row>
        <el-col :span="6" v-if="$store.state.showAgent">
          <el-form-item label="区域">
            <el-select style="width:100%" v-model="params.id" filterable clearable default-first-option placeholder="--区域--" @change="changeId">
              <el-option v-for="item in restaurants" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
       <el-col :span="6">
          <el-form-item label="所属BD">
            <el-select style="width: 100%" @change="getTableList()" :disabled="$store.state.type === 5" v-model="params.bdId" filterable clearable placeholder="--所属BD--">
              <el-option v-for="items in businessDevelopmentList" :key="'businessDevelopmentList'+items.id" :label="items.name" :value="items.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span='6'>
          <el-form-item label="日期">
            <pt-date-picker v-model="params.date" :shortcuts="[{ text: '今天', start: 0, end: 0}, { text: '昨天', start: -1, end: 0},
              { text: '近七天', start: -7, end: 0}, {text: '近一个月', start: -30, end: 0}]" />
          </el-form-item>
        </el-col>
        <el-col :span="$store.state.showAgent? 6: 12" style="text-align:right;">
          <el-form-item label-width="0">
            <el-button type="primary" icon="el-icon-search" @click="getTableList()">查询</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-tabs v-model="pageIndex">
      <el-tab-pane label="趋势图" name="1">
        <div class="item-wrap">
          <div class="item">
            <div class="head">订单数据</div><div class="rice" id="salePrice1"></div>
          </div>
          <div class="item">
            <div class="head">盈收数据</div><div class="rice" id="salePrice2"></div>
          </div>
          <div class="item">
            <div class="head">取消率</div><div class="rice" id="salePrice3"></div>
          </div>
          <div class="item">
            <div class="head">GMV</div><div class="rice" id="salePrice4"></div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="表格统计" name="2">
        <el-row type="flex" justify="end">
          <el-button @click="exportExcel()">导出表格<i class="el-icon-download"></i></el-button>
        </el-row>
        <div class="base-table-wrap">
          <el-table :data="tableData.orderDaily"  max-height="650" :summary-method="getSummaries" show-summary id="out-table">
            <el-table-column prop="date" label="日期" min-width="100px" align="left" />
            <el-table-column prop="quantity35" min-width="130px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="已支付的订单，折前商品总额，不含配送费" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>原抽佣营业额
              </template>
            </el-table-column>
            <el-table-column prop="quantity36" min-width="130px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="已支付的订单，按实际设置的折前或折后的抽佣方式计算出的商品总额，不含配送费" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>实抽佣营业额
              </template>
            </el-table-column>
            <el-table-column prop="quantity11" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="按折前抽佣方式计算出的可收入的抽佣金额，不含配送费" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>原抽佣盈收
              </template>
            </el-table-column>
            <el-table-column prop="quantity12" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="按实际设置的折前或折后的抽佣方式计算出的可抽佣金额，不含配送费" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>实抽佣盈收
              </template>
            </el-table-column>
            <el-table-column prop="quantity13" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="外卖订单配送费活动前应收入金额，不包含跑腿订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>原配送盈收
              </template>
            </el-table-column>
            <el-table-column prop="quantity33" min-width="120px" align="right" >
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="外卖订单配送费活动前收入-区域配送费活动支出=实配送盈收，不包含跑腿订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>实配送盈收
              </template>
            </el-table-column>
            <el-table-column prop="quantity1" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="已完成的有效订单，支付后取消或其他全额退款的订单除外" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>有效订单量
              </template>
            </el-table-column>
            <el-table-column prop="quantity4" min-width="130px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="由平台提供配送的订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>平台配送订单
              </template>
            </el-table-column>
            <el-table-column prop="quantity5" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="由商家自行配送的订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>自配送订单
              </template>
            </el-table-column>
            <el-table-column prop="quantity3" min-width="130px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="下单后未支付的订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>未支付取消单
              </template>
            </el-table-column>
            <el-table-column min-width="130px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="单后未支付的订单/全部订单=未支付订单率" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>未支付取消率
              </template>
              <template slot-scope="scope">{{scope.row.quantity34}}%</template>
            </el-table-column>
            <el-table-column prop="quantity2" min-width="120px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="实际支付后取消或其他全额退款的订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>全额退款单
              </template>
            </el-table-column>
            <el-table-column min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="退款单/有效订单=退款率" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>退款率
              </template>
              <template slot-scope="scope">{{scope.row.quantity22}}%</template>
            </el-table-column>
            <el-table-column prop="quantity10" min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="用户实际支付的金额" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>交易额
              </template>
            </el-table-column>
            <el-table-column prop="quantity16" min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="(实抽佣营业额+原配送盈收)/有效订单量=客单价" placement="top">
                  <el-button icon="el-icon-question" type="text" />>
                </el-tooltip>客单价
              </template>
            </el-table-column>
            <el-table-column prop="quantity0" min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="有效订单+未付款的订单+退款单=总订单" placement="top">
                  <el-button icon="el-icon-question" type="text" />>
                </el-tooltip>总订单
              </template>
            </el-table-column>
            <el-table-column prop="quantity8" min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="订单的折前金额，包含订单已付款+未付款+退款单的总额" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>毛GMV
              </template>
            </el-table-column>
            <el-table-column prop="quantity9" min-width="100px" align="right">
              <template slot="header" slot-scope="scope">
                <el-tooltip effect="dark" content="订单的折后金额，包含订单已付款+未付款+退款单的总额" placement="top">
                  <el-button icon="el-icon-question" type="text" />
                </el-tooltip>净GMV
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>
    <pt-table-loading v-show="isloadingTable" />
  </div>
</template>
<script>
  import { getDay } from '@/utils/ptkc.js'
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
  import 'echarts/theme/macarons.js'
  import acction from '@/utils/acction.js'
  import { businessDevelopment } from '@/api/busnt.js'
  import { order } from '@/api/data.js'
  export default {
    data() {
      return {
        params: {
          id: '',
          bdId: null,
          date: [getDay(-30) + ' ' + '00:00:00', getDay(0) + ' ' + '23:59:59']
        },
        isChangeWindow: false, // 窗口在列表页发生变化
        isloadingTable: false, //获取数据
        tableData: { }, // 获取到的数据
        businessDevelopmentList: [], //BD列表
        pageIndex: '1', // 切换
        curParams: {}, // 请求数据的
        myChart1: null,
        myChart2: null,
        myChart3: null,
        myChart4: null
      }
    },
    computed: {
      restaurants() { // 区域据
        return this.$store.state.agentList
      }
    },
    watch: {
      restaurants: {
        handler(val) {
          if (val && val.length ===1) {
            this.params.id = val[0].id
          }
        },
        deep: true
      },
      'params.id': {
        handler(val, old) {
          if (val) {
            this.getBusinessDevelopment(val)
          } else {
            this.businessDevelopmentList = []
          }
        },
        deep: true
      },
      pageIndex(val) { // 防止列表窗口变化导致变形
        if (val === '1' && this.isChangeWindow) {
          this.isChangeWindow = false
          this.$nextTick(() => {
            this.myChart1.resize()
            this.myChart2.resize()
            this.myChart3.resize()
            this.myChart4.resize()
          })
        } 
      },
      '$store.state.screenRice': {
        handler(val) {
          if (this.myChart1) {
            if (this.pageIndex === '1') {
              this.myChart1.resize()
              this.myChart2.resize()
              this.myChart3.resize()
              this.myChart4.resize()
            } else {
              this.isChangeWindow = true
            }
          }
        },
        deep: true
      }
    },
    methods: {
      changeId() { // 切换代理
        this.params.bdId = null
        this.getTableList()
      },
      getSummaries(param) { // 表单总计
        const {columns, data} = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = '总计'
            return
          }
          if (column.property === 'quantity34' || column.property === 'quantity22') {
            sums[index] = 'N/A'
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) return new acction(prev,curr).accAdd()
              else return prev
            }, 0)
          } else {
            sums[index] = 'N/A'
          }
        })
        return sums
      },
      exportExcel() { // 下载表格
        var wb = XLSX.utils.table_to_book(document.querySelector('#out-table')) /* generate workbook object from table */
        var wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'}) /* get binary string as output */
        const str = `${this.curParams.startDate.slice(0, 10)} - ${this.curParams.endDate.slice(0, 10)}订单统计.xlsx`
        try {
          FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), str)
        } catch (e) {
          if (typeof console !== 'undefined') console.log(e, wbout)
        }
        return wbout
      },
      drawSalePrice() { // 订单量
        const orderName = ['总订单','有效订单', '全额退款单', '未支付单']
        const grid = { left: 70, top: 30, right: 70 }
        this.myChart1 = this.$echarts.init(document.getElementById('salePrice1'), 'macarons')
        this.myChart1.setOption({
          legend:{ data: orderName },
          color:['#bad778', '#ff967d', '#bb73cb', '#508df9'],
          tooltip: { trigger: 'axis'},
          grid: grid, // 距离容器上边像素
          xAxis: [{ 
            type: 'category', splitLine: { show: true}, axisLine:{ lineStyle:{ color:'#333', width: 1 }},
            data: this.tableData.orderDaily.map(item => item.date.slice(5))
          }],
          yAxis: [{ type: 'value', axisLine:{ lineStyle:{ color:'#333', width: 1 }} }],
          series: [{
            name:'总订单', type:'bar', data: this.tableData.orderDaily.map(i =>i['quantity0'])
          },{
            name:'有效订单', type:'bar', stack: '所有', data: this.tableData.orderDaily.map(i =>i['quantity1'])
          },{
            name:'全额退款单', type:'bar', stack: '所有', data: this.tableData.orderDaily.map(i =>i['quantity2'])
          },{
            name:'未支付单', type:'bar', stack: '所有', data: this.tableData.orderDaily.map(i =>i['quantity3'])
          }]
        })
        //异常单
        this.myChart2 = this.$echarts.init(document.getElementById('salePrice2'), 'macarons')
        this.myChart2.setOption({
          legend:{ data: ['原抽佣盈收', '实抽佣盈收', '原配送盈收', '实配送盈收']},
         color:['#bad778', '#ff967d', '#bb73cb', '#508df9'],
          grid: grid, // 距离容器上边像素
          tooltip: { trigger: 'axis' },
          xAxis: [{ 
            type: 'category', splitLine: { show: true}, data: this.tableData.orderDaily.map(item => item.date.slice(5)),
            axisLine:{ lineStyle:{ color:'#333', width: 1 }}, boundaryGap: false,
          }],
          yAxis: [{ type: 'value', axisLabel: {show: true, interval: 'auto'}, axisLine:{ lineStyle:{ color:'#333', width: 1 }} }],
          series:[{ 
            name: '原抽佣盈收', type:'line', lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity11']), 
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#bad778' }, { offset: 1, color: '#fdfcfc' }]
            }}
          },{
            name: '实抽佣盈收', type:'line', lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity12']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#ff967d' }, { offset: 1, color: '#fdfcfc' }]
            }}
          },{
            name: '原配送盈收', type:'line', lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity13']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#bb73cb' }, { offset: 1, color: '#fdfcfc' }]
            }}
          },{
            name: '实配送盈收', type:'line',lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity33']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#508df9' }, { offset: 1, color: '#fdfcfc' }]
            }}
          }]
        })
        this.myChart3 = this.$echarts.init(document.getElementById('salePrice3'), 'macarons')
        this.myChart3.setOption({
          legend:{ data: ['完成率', '退款率', '未支付订单率']},
          color:['#bad778', '#ff967d', '#bb73cb'],
          grid: grid, // 距离容器上边像素
          tooltip: { trigger: 'axis', formatter: (params) => {
            let str = `<div><p>${params[0].name.split('[')[0]}</p></div>`
            for (let i = 0; i< params.length; i++) {
              str += `${params[i].marker} ${params[i].seriesName}: ${params[i].data}%<br />`
            }
            return str
          }},
          xAxis: [{ 
            type: 'category', splitLine: { show: true}, axisLine:{ lineStyle:{ color:'#333', width: 1 }},
            data: this.tableData.orderDaily.map(item => item.date.slice(5)), boundaryGap: false,
          }],
           yAxis: [{ 
            type: 'value', axisLabel: {show: true, interval: 'auto', formatter: '{value}%' }, 
            axisLine:{ lineStyle:{ color:'#333', width: 1 }} 
          }],
          series:[{ 
            name: '完成率', type:'line', lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity19']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#bad778' }, { offset: 1, color: '#fdfcfc' }]
            }}
          },{
            name: '退款率', type:'line',lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity22']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#ff967d' }, { offset: 1, color: '#fdfcfc' }]
            }}
          },{
            name: '未支付订单率', type:'line', lineStyle:{ width: 1 }, data:this.tableData.orderDaily.map(i =>i['quantity34']),
            areaStyle: { color: { 
              type: 'linear', x: 0, y: 0, x2: 0, y2: 1, global: false, // 缺省为 false
              colorStops: [{ offset: 0, color: '#bb73cb' }, { offset: 1, color: '#fdfcfc' }]
            }}
          }]
        })
        this.myChart4 = this.$echarts.init(document.getElementById('salePrice4'), 'macarons')
        this.myChart4.setOption({
          legend:{ data: ['毛GMV', '净GMV'] },
          tooltip: { trigger: 'axis',axisPointer: {  animation: false }},
          color:['#cdd6e6', '#ff967d'],
          grid: grid, // 距离容器上边像素
          xAxis: [{ 
            type: 'category', splitLine: { show: true}, axisLine:{ lineStyle:{ color:'#333', width: 1 }},
            data: this.tableData.orderDaily.map(item => item.date.slice(5))
          }],
          yAxis: [{ type: 'value', axisLine:{ lineStyle:{ color:'#333', width: 1 }} }],
          series:[{ 
            name: '毛GMV', type:'bar', smooth: true, 
            data:this.tableData.orderDaily.map(i =>i['quantity8'])
          },{
            name: '净GMV', type:'line', smooth: true, lineStyle:{ width: 1 },
            data:this.tableData.orderDaily.map(i =>i['quantity9'])
          }]
        })
      },
      getTableList() {
        const params = { ...this.params }
        params.startDate = params.date ? params.date[0] : ''
        params.endDate = params.date ? params.date[1] : ''
        delete  params.date
        this.isloadingTable = true
        order(params).then(res => {
          if (res.success) {
            this.curParams = params
            this.tableData = res.data
            this.drawSalePrice()
          }
        }).finally(() => { this.isloadingTable = false })
      },
      getBusinessDevelopment(agentId) { // 获取BD数据
        businessDevelopment({ agentId }).then(res => {
          if (res.success) {
            this.businessDevelopmentList = res.data
            if (this.$store.state.type === 5) this.params.bdId = this.businessDevelopmentList[0].id || ''
          }
        })
      }
    },
    mounted() {
      if (this.restaurants && this.restaurants.length === 1) {
        this.params.id = this.restaurants[0].id
      }
      this.getTableList()
    }
  }
</script>
<style lang="scss" scoped>
  .item-wrap{
    width: 100%;
    display: flex;
    flex-flow: row wrap;
    background: #fff;
    .item{
      width: 50%;
      height: 500px;
      box-sizing: border-box;
      .head{
        padding: 0 30px;
        height: 40px;
        font-size: 20px;
        font-weight: bold;
      }
      .rice{
        width: 100%;
        height: 450px;
      }
    }
  }
</style>
